package com.whimscrew.dept.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.whimscrew.dept.model.Dept;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class DeptService {


    @Autowired
    private RedisTemplate redisTemplate;

    @HystrixCommand(
        //后备方法，参数要求一致
        fallbackMethod = "buildFallbackSave",
        commandProperties={
            //超时时间
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="2000")
        }
    )
    public Dept save(String username) {
        //模仿数据库随机出现的耗时操作
        Random random = new Random();
        int second = random.nextInt(3000) ;
        if (second > 2000){
            System.out.println(" dept耗时： "+ second);
        }
        try {
            Thread.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
        if(redisTemplate.hasKey(username)){
            return (Dept) redisTemplate.opsForValue().get(username);
        }
        //随机英文字符设置
        String deptName = RandomStringUtils.randomAlphanumeric(5);
        Dept saveData = new Dept(UUID.randomUUID().toString(),deptName );
        redisTemplate.opsForValue().set(username,saveData,1, TimeUnit.HOURS);
        return saveData;
    }


    /**
     * 断路器后备方法
     */
    public Dept buildFallbackSave(String username){
        System.out.println(" 后备方案 ");
        //随机中文字符设置
        String deptName = RandomStringUtils.random(4, 0x4e00, 0x9fa5, false, false);
        Dept saveData = new Dept(UUID.randomUUID().toString(),deptName );
        redisTemplate.opsForValue().set(username,saveData,1, TimeUnit.HOURS);
        return saveData;
    }

}
